<template>
  <div class="dashboard-container">
    <!-- :gutter 表示设置间距为20px -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #40c9c6;">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics.total_users }}</div>
              <div class="stat-label">总用户数</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #36a3f7;">
              <el-icon><UserFilled /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics.active_users }}</div>
              <div class="stat-label">活跃用户</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #f4516c;">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics.new_users_today }}</div>
              <div class="stat-label">今日新增</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #4fc08d;">
              <el-icon><Monitor /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{statistics.system_status}}</div>
              <div class="stat-label">系统状态</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <div ref="lineChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card class="chart-card">
          <div ref="barChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <div ref="pieChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card class="chart-card">
          <div class="recent-activity">
            <h3>最近活动</h3>
            <el-timeline>
              <el-timeline-item
                v-for="(activity, index) in recentActivities"
                :key="index"
                :timestamp="activity.timestamp"
                placement="top"
              >
                <el-card>
                  <h4>{{ activity.title }}</h4>
                  <p>{{ activity.content }}</p>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
  import {ref, reactive, onMounted, onBeforeUnmount} from 'vue'
  import * as echarts from 'echarts'
  import { dashboardAPI } from '../../api'

  // 图表引用
  const lineChartRef = ref()
  const barChartRef = ref()
  const pieChartRef = ref()

  // 图表实例
  let lineChart = null
  let barChart = null
  let pieChart = null

  // 统计数据
  const statistics = reactive({
    total_users: 0,
    active_users: 0,
    new_users_today: 0,
    system_status: '正常'
  })

  // 最近活动
  const recentActivities = ref([
    {
      title: '新用户注册',
      content: '用户张三注册了系统',
      timestamp: '2025-08-15 10:30'
    },
    {
      title: '系统更新',
      content: '系统更新到v1.0.1版本',
      timestamp: '2025-08-12 15:30'
    },
    {
      title: '安全检查',
      content: '完成系统安全检查',
      timestamp: '2025-08-10 09:30'
    }
  ])

  // 加载统计数据
  const loadStatistics = async () => {
    try {
      const data = await dashboardAPI.getStatistics()
      // 从dashboardAPI.getStatistics()获取到的数据data合并到statics对象中，更新其属性值
      Object.assign(statistics, data)
    } catch (error) {
      console.error('加载统计数据失败:', error)
    }
  }

  // 加载图表数据
  const loadChartData = async () => {
    try {
      // 线图数据
      const lineData = await dashboardAPI.getChartData('line')
      renderLineChart(lineData)

      // 柱图数据
      const barData = await dashboardAPI.getChartData('bar')
      renderBarChar(barData)

      // 饼图数据
      const pieData = await dashboardAPI.getChartData('pie')
      renderPieChart(pieData)
    } catch (error) {
      console.error('加载图表数据失败:',error)
    }
  }

  // 渲染线图
  const renderLineChart = (data) => {
    if(!lineChartRef.value) return
    if(!lineChart) {
      lineChart = echarts.init(lineChartRef.value)
    }
    const option = {
      title: {
        text: data.title
      },
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: data.labels
      },
      yAxis: {
        type: 'value'
      },
        series: [{
          data: data.data,
          type: 'line',
          smooth: true
        }]
    }
    lineChart.setOption(option)
  }

  // 渲染柱图
  const renderBarChar = (data) => {
    if(!barChartRef.value) return
    if(!barChart) {
      barChart = echarts.init(barChartRef.value)
    }

    const option = {
      title: {
        text: data.title
      },
      tooltip: {},
      xAxis: {
        type: 'category',
        data: data.labels
      },
      yAxis: {},
      series: [{
        data: data.data,
        type: 'bar'
      }]
    }
    barChart.setOption(option)
  }

  // 渲染饼图
  const renderPieChart = (data) => {
    // pieChartRef是一个响应式引用ref,它本身是一个对象，对象中有一个value属性，它是实际的dom元素或组件实例
    // 在模板中使用ref时，需要通过.value访问其绑定的具体值
    if(!pieChartRef.value) return
    if(!pieChart) {
      pieChart = echarts.init(pieChartRef.value)
    }
    const seriesData = data.labels.map((label,index) => ({
      name: label,
      value: data.data[index]
    }))

    const option = {
      title: {
        text: data.title,
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [{
        type: 'pie',
        radius: '50%',
        data: seriesData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    }
    pieChart.setOption(option)
  }

  // 窗口大小变化时重绘图表
  const handleResize = () => {
    if (lineChart) lineChart.resize()
    if (pieChart) pieChart.resize()
    if (barChart) barChart.resize()
  }

  // 组件挂载
  onMounted(() => {
    loadStatistics()
    loadChartData()
    // 监听窗口大小变化
    window.addEventListener('resize', handleResize)
  })

  // 组件卸载前清理
  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize)
    if (lineChart) lineChart.dispose()
    if (pieChart) pieChart.dispose()
    if (barChart) barChart.dispose()
  })
</script>

<style scoped>
  .dashboard-container {
    padding: 20px;
  }
  .stats-row {
    margin-bottom: 20px;
  }
  .stat-card {
    border-radius: 8px;
  }
  .stat-content {
    display: flex;
    align-items: center;
  }
  .stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 15px;
  }
  .stat-icon .el-icon {
    font-size: 24px;
    color: #fff;
  }
  .stat-info {
    flex: 1;
  }
  .stat-number {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 5px;
  }
  .stat-label {
    font-size: 14px;
    color: #999;
  }
  .charts-row {
    margin-bottom: 20px;
  }
  .chart-card {
    border-radius: 8px;
  }
  .chart-container {
    width: 100%;
    height: 300px;
  }

  .recent-activity h3 {
    margin-bottom: 20px;
  }
</style>
